package com.zz.kt.activity.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zz.kt.activity.mapper.CouponInfoMapper;
import com.zz.kt.activity.service.CouponInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zz.kt.activity.service.CouponUseService;
import com.zz.kt.client.user.UserInfoFeignClient;
import com.zz.kt.model.activity.CouponInfo;
import com.zz.kt.model.activity.CouponUse;
import com.zz.kt.model.user.UserInfo;
import com.zz.kt.vo.activity.CouponInfoVo;
import com.zz.kt.vo.activity.CouponUseQueryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 优惠券信息 服务实现类
 * </p>
 *
 * @author zz
 * @since 2022-09-05
 */
@Service
public class CouponInfoServiceImpl extends ServiceImpl<CouponInfoMapper, CouponInfo> implements CouponInfoService {

    @Autowired
    private CouponUseService couponUseService;

    @Autowired
    private UserInfoFeignClient userInfoFeignClient;

    //获取已经使用优惠卷列表(条件查询分页)
    @Override
    public IPage<CouponUse> selectCouponUsePage(Page<CouponUse> pageParam, CouponUseQueryVo couponUseQueryVo) {
        //获取条件
        Long couponId = couponUseQueryVo.getCouponId();
        String couponStatus = couponUseQueryVo.getCouponStatus();
        String getTimeBegin = couponUseQueryVo.getGetTimeBegin();
        String getTimeEnd = couponUseQueryVo.getGetTimeEnd();

        //封装条件
        QueryWrapper<CouponUse> wrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(couponId)) {
            wrapper.eq("coupon_id",couponId);
        }
        if(!StringUtils.isEmpty(couponStatus)) {
            wrapper.eq("coupon_status",couponStatus);
        }
        if(!StringUtils.isEmpty(getTimeBegin)) {
            wrapper.ge("get_time",getTimeBegin);
        }
        if(!StringUtils.isEmpty(getTimeEnd)) {
            wrapper.le("get_time",getTimeEnd);
        }

        //调用方法查询
        IPage<CouponUse> pageModel = couponUseService.page(pageParam, wrapper);
        List<CouponUse> records = pageModel.getRecords();
        //遍历
        records.stream().forEach(item ->{
            this.getUserInfoById(item);
        });

        return pageModel;
    }

    //更新优惠卷
    @Override
    public void updateCouponInfoUseStatus(Long couponUseId, Long orderId) {
        try {
            CouponUse couponUse = new CouponUse();
            couponUse.setId(couponUseId);
            couponUse.setOrderId(orderId);
            couponUse.setCouponStatus("1");

            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String format = sdf.format(date);
            Date dateR = sdf.parse(format);

            couponUse.setUsingTime(dateR);
            couponUseService.updateById(couponUse);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Map<String, Object> findCouponInfo() {
        //修改时间格式
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = sdf.format(date);

        //查询过期的优惠卷
        LambdaQueryWrapper<CouponInfo> wrapperDis = new LambdaQueryWrapper<>();
        wrapperDis.le(CouponInfo::getExpireTime,time);
        List<CouponInfo> disabledCouponsListTest = baseMapper.selectList(wrapperDis);

        //封装到Vo中
        List<CouponInfoVo> disabledCouponsList =new ArrayList<>();
        disabledCouponsListTest.stream().forEach(item ->{
            CouponInfoVo couponInfoVo = this.transfrom(item);
            disabledCouponsList.add(couponInfoVo);
        });

        //查询未过期的优惠卷
        LambdaQueryWrapper<CouponInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.le(CouponInfo::getCreateTime,time);
        wrapper.ge(CouponInfo::getExpireTime,time);
        List<CouponInfo> abledCouponsListTest = baseMapper.selectList(wrapper);
        //封装
        List<CouponInfoVo> abledCouponsList =new ArrayList<>();
        abledCouponsListTest.stream().forEach(item ->{
            CouponInfoVo couponInfoVo = this.transfrom(item);
            abledCouponsList.add(couponInfoVo);
        });

        //封装到一个map中
        Map<String,Object> map = new HashMap<>();
        map.put("disabledCouponsList",disabledCouponsList);
        map.put("abledCouponsList",abledCouponsList);

        return map;
    }

    //封装到Vo中
    private CouponInfoVo transfrom(CouponInfo item) {
        CouponInfoVo couponInfoVo = new CouponInfoVo();
        couponInfoVo.setId(item.getId());
        couponInfoVo.setAvailable(item.getPublishCount());
        couponInfoVo.setCondition(item.getRuleDesc());
        couponInfoVo.setReason("已过期");
        couponInfoVo.setValue(item.getAmount().stripTrailingZeros().toPlainString());
        couponInfoVo.setName(item.getCouponName());
        couponInfoVo.setStartAt(item.getStartTime().getTime());
        couponInfoVo.setEndAt(item.getEndTime().getTime());
        int amount = item.getAmount().intValue() /100;
        couponInfoVo.setValueDesc(String.valueOf(amount));//折扣券优惠金额文案
        couponInfoVo.setUnitDesc("元");//单位文案
        return couponInfoVo;
    }

    //根据用户id，通过远程调用得到用户信息
    private CouponUse getUserInfoById(CouponUse couponUse) {
        //获取用户id
        Long userId = couponUse.getUserId();
        if (!StringUtils.isEmpty(userId)){
            //远程调用
            UserInfo userInfo = userInfoFeignClient.getById(userId);
            if (userInfo != null){
                couponUse.getParam().put("nickName",userInfo.getNickName());
                couponUse.getParam().put("phone", userInfo.getPhone());
            }
        }
        return couponUse;
    }
}
